package cn.wolfcode.luowowo2.website.web.param;

import cn.wolfcode.luowowo2.cache.prefix.UserInfoKeyPrefix;
import cn.wolfcode.luowowo2.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo2.member.domain.UserInfo;
import cn.wolfcode.luowowo2.util.CookieUtil;
import cn.wolfcode.luowowo2.website.web.annotation.UserParam;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by Albert on 2019/7/8.
 */
public class  UserInfoArgumentResolver implements HandlerMethodArgumentResolver {
    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(UserParam.class) && methodParameter.getParameterType()== UserInfo.class;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {

        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        Cookie cookie = CookieUtil.getCookie(request, UserInfoKeyPrefix.USER_INFO_TOKEN_COOKIE_NAME);
        UserInfo userInfo= null;
        if (cookie!=null) {
            userInfo = userInfoRedisService.getUserInfoByToken(UserInfoKeyPrefix.USER_INFO_TOKEN, cookie.getValue());
        }
        return userInfo;
    }
}
